import { ObjectId } from 'mongodb'
import * as db from '../db'
import { stats } from '../stats'
import { AdvicesType, Connect, DingdanStat, IBooks, Relevance } from '../types'
import { addSome, removeSome, checkSome, stoObjId, cTob, Stock } from './tools'

// 添加订单 //批量下单
export async function addDingdan(
  value: {
    allprice: number
    name: string
    phone: number
    note: string
    cartIds: string[]
    address: string
  },
  userId: ObjectId
) {
  const { allprice, cartIds } = value
  // 付钱
  await db.userCollection.findOneAndUpdate(
    { _id: userId },
    { $inc: { mdb: -allprice } }
  )
  // 库存减少
  const others = stoObjId(cartIds)
  await Stock(others, -1)

  // 计入订单表
  const res = await db.dingdansCollection.insertOne({
    _id: null,
    ...value,
    cartIds: others,
    userId,
    isDelete: false,
    createAt: Date.now()
  })
  if (res.insertedId) {
    // 买方录入中间表
    await addSome(userId, res.insertedId, Relevance.Dingdan)
    // 移除购物车 你这
    await db.connectCollection.updateMany(
      { _id: { $in: others } },
      { $set: { type: Relevance.Mycared, confirm: DingdanStat.Waiting } }
    )
    // 告知卖方你的书有人买了

    others.forEach(async item => {
      const mids = await db.connectCollection.findOne(
        { _id: item },
        { projection: { destId: 1 } }
      )
      const book = await db.booksCollection.findOne(
        { _id: mids.destId },
        { projection: { publisher: 1 } }
      )
      await db.advicesCollection.insertOne({
        _id: null,
        userId: book.publisher,
        destId: res.insertedId,
        cartId: item,
        bookId: mids.destId,
        time: Date.now(),
        seen: false,
        type: AdvicesType.Maichuing
      })
    })
  }
}

export async function Dingdanlist(value: any) {
  const { userId, skip, limit } = value
  const userid = new ObjectId(userId)
  const total = await db.dingdansCollection.find({ userId: userid }).count()
  const dingdans = await db.dingdansCollection
    .aggregate([
      { $match: { userId: userid } },
      {
        $lookup: {
          from: 'connect',
          localField: 'cartIds',
          foreignField: '_id',
          as: 'cart'
        }
      },
      { $unwind: '$cart' },
      { $sort: { createAt: 1 } },
      { $skip: skip },
      { $limit: limit },
      {
        $project: {
          _id: 1,
          createAt: 1,
          cart: {
            _id: 1,
            names: 1,
            allprice: 1,
            destId: 1,
            confirm: 1
          }
        }
      }
    ])
    .toArray()

  const list: {}[] = []
  for (const item of dingdans) {
    const book = await db.booksCollection.findOne(
      { _id: item.cart.destId },
      {
        projection: { banner: 1, title: 1 }
      }
    )
    list.push({ ...item, banner: book.banner[0], title: book.title })
  }
  return { list, total }
}

export async function confirm(value: any, userId: ObjectId) {
  const { cartId, flag } = value

  const _id = new ObjectId(cartId)
  // 要给个限制,只等待时候能操作
  const cart = await db.connectCollection.findOne({ _id })

  // 打钱
  if (cart.confirm === DingdanStat.Daohuo && flag) {
    await db.connectCollection.findOneAndUpdate(
      { _id },
      { $set: { confirm: DingdanStat.Queren } }
    )

    // 加入购买表
    await addSome(userId, _id, Relevance.Goumai)

    const book = await db.booksCollection.findOne(
      { _id: cart.destId },
      { projection: { publisher: 1 } }
    )

    // 打钱 卖方录入中间表 --- >有毛病
    await db.userCollection.findOneAndUpdate(
      { _id: book.publisher },
      { $inc: { mdb: cart.allprice } }
    )

    // 加入卖出表
    await db.connectCollection.insertOne({
      _id: null,
      userId: book.publisher,
      destId: _id,
      time: Date.now(),
      type: Relevance.Maichu
    })
  } else if (cart.confirm === DingdanStat.Waiting && !flag) {
    await db.connectCollection.findOneAndUpdate(
      { _id },
      { $set: { confirm: DingdanStat.Cancel } }
    )
    // 如果取消订单,库存加回去
    await Stock([_id], 1)
    // 钱也打回
    await db.userCollection.findOneAndUpdate(
      { _id: userId },
      { $inc: { mdb: cart.allprice } }
    )
  }
}

export async function detail(value: any, userId: ObjectId) {
  const { dingdanId, cartId } = value

  const cartid = new ObjectId(cartId)
  const _id = new ObjectId(dingdanId)
  const res = await checkSome(userId, _id, Relevance.Dingdan)
  if (!res) throw stats.ERR_NOT_RIGHT
  const data = await db.dingdansCollection.findOne({ _id })
  const cart = await db.connectCollection.findOne(
    { _id: cartid },
    { projection: { destId: 1, names: 1, prices: 1, confirm: 1 } }
  )
  const book = await db.booksCollection.findOne(
    { _id: cart.destId },
    { projection: { title: 1, banner: 1 } }
  )
  return { ...data, book, cart }
}

export async function list(ids: string[]) {
  // 传入的应该是订单的中间表id
  const mids = stoObjId(ids)
  const rows = db.connectCollection
    .aggregate([
      { $match: { _id: { $in: mids } } },
      {
        $lookup: {
          from: 'books',
          localField: 'destId',
          foreignField: '_id',
          as: 'book'
        }
      },
      { $unwind: '$book' },
      {
        $project: {
          allprice: 1,
          names: 1,
          book: {
            _id: 1,
            title: 1,
            banner: 1
          }
        }
      }
    ])
    .toArray()
  return rows
}

// 通知发货列表  告知卖方你的书有人买了
export async function sendlist(value: any, userId: ObjectId) {
  const { skip, limit } = value
  const list = await db.advicesCollection
    .aggregate([
      { $match: { userId } },
      {
        $lookup: {
          from: 'dingdans',
          localField: 'destId',
          foreignField: '_id',
          as: 'dingdan'
        }
      },
      {
        $lookup: {
          from: 'connect',
          localField: 'cartId',
          foreignField: '_id',
          as: 'cart'
        }
      },
      {
        $lookup: {
          from: 'books',
          localField: 'bookId',
          foreignField: '_id',
          as: 'book'
        }
      },
      { $unwind: '$dingdan' }, // 我的目的是不把多余的书暴露了
      { $unwind: '$book' },
      { $unwind: '$cart' },
      { $sort: { time: -1 } },
      { $skip: skip },
      { $limit: limit },
      {
        $project: {
          seen: 1,
          time: 1,
          type: 1,
          dingdan: {
            name: 1,
            address: 1,
            phone: 1,
            note: 1,
            userId: 1
          },
          cart: {
            names: 1,
            prices: 1,
            allprice: 1,
            confirm: 1
          },
          book: { _id: 1, books: 1, title: 1 }
        }
      }
    ])
    .toArray()
  const total = await db.advicesCollection.find({ userId }).count()
  return { list, total }
}

export async function see(advId: string) {
  const _id = new ObjectId(advId)
  const res = await db.advicesCollection.findOneAndUpdate(
    { _id },
    { $set: { seen: true } }
  )
  return res.value
}

// 货物到达地点
export async function arrival(advId: string, flag: boolean) {
  const _id = new ObjectId(advId)
  const adv = await db.advicesCollection.findOne({ _id })

  const buyer = await db.connectCollection.findOne(
    { _id: adv.cartId },
    { projection: { userId: 1, allprice: 1 } }
  )
  const type = flag ? AdvicesType.Arrival : AdvicesType.Empty
  await db.advicesCollection.insertOne({
    _id: null,
    userId: buyer.userId,
    destId: adv.destId,
    cartId: adv.cartId,
    bookId: adv.bookId,
    time: Date.now(),
    seen: false,
    type
  })

  const confirm = flag ? DingdanStat.Daohuo : DingdanStat.Empty
  await db.connectCollection.findOneAndUpdate(
    { _id: adv.cartId },
    { $set: { confirm } }
  )
  if (!flag) {
    // 钱也打回
    await db.userCollection.findOneAndUpdate(
      { _id: buyer.userId },
      { $inc: { mdb: buyer.allprice } }
    )
  }
}
